package com.zsj.zsjkotlinmvvm.ui.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYStateUiListener;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.GSYVideoType;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.zsj.zsjkotlinmvvm.R;
import com.zsj.zsjkotlinmvvm.utils.CarGuo;
import com.zsj.zsjkotlinmvvm.utils.NetworkUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

public class VideoPlayerView extends StandardGSYVideoPlayer implements LifecycleObserver {

    public static final String TAG = VideoPlayerView.class.getSimpleName();
    private CallBack mCallBack;
    private SeekOnStartCallBack mSeekOnStartCallBack;
    private LifecycleOwner mLifecycleOwner;
    private ImageView ivVideoCover;
    private ImageView ivPlay;

    public boolean canResume = false;
    private LinearLayout llTitleBarLand;

    private TextView currentLand, totalLand, titleLand;
    private ViewGroup ctlContainerLand;
    private FrameLayout flSeekBarParentLand, flFull;
    private SeekBar progressLand;

    private FrameLayout flCenterPlay;//中间播放视图、播放在线视频失败且无网络时隐藏，否者显示
    public OrientationUtils orientationUtils;
    public AsyncTask<Void, Void, Void> mPlayTask;
    public String url/*标清、本地路径或高清*/;
    public static String id;//当前播放id
    private WeakReference<FragmentActivity> mActivity;

    private ConstraintLayout flNotNetLand;
    private TextView tvCheckNetLand, tvNetCancel;

    //是否可以统计 开启播放设置为true 统计一次设置为false
    public boolean canStatistics;

    //是否只显示全屏
    public final boolean isOnlyLand = false;
    /**
     * 回调到VideoActivity中
     */
    private GSYStateUiListener mPlayStateListener;
    private RelativeLayout surfaceContainer;


    public void setPlayStateListener(GSYStateUiListener mPlayStateListener) {
        this.mPlayStateListener = mPlayStateListener;
    }


    public VideoPlayerView(Context context) {
        super(context);
        initView();
    }

    public VideoPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    @Override
    public int getLayoutId() {
        return R.layout.layout_video_play;
    }

    private void initView() {
        ivVideoCover = new ImageView(mContext);
        //  设置播放器
        ivVideoCover.setScaleType(ImageView.ScaleType.FIT_XY);
        //设置视频封面
        setThumbImageView(ivVideoCover);
        llTitleBarLand = findViewById(R.id.ll_title_bar_land);
        ivPlay = findViewById(R.id.iv_play);
        titleLand = findViewById(R.id.tv_title_land);
        surfaceContainer = findViewById(R.id.surface_container);
        ctlContainerLand = findViewById(R.id.ctl_container_land);
        progressLand = findViewById(R.id.progress);
        flSeekBarParentLand = findViewById(R.id.fl_seek_bar_parent_land);
        currentLand = findViewById(R.id.current);
        totalLand = findViewById(R.id.total);
        //中间播放
        flCenterPlay = findViewById(R.id.fl_center_play);
        //开始播放
        ivPlay.setOnClickListener(v -> playVideo());
        //返回
        llTitleBarLand.setOnClickListener(new backClickListener());
        //滑动进度条
        flSeekBarParentLand.setOnTouchListener(mSeekBarParentTouchListener);
        progressLand.setOnSeekBarChangeListener(this);
        progressLand.setOnClickListener(this);
        //触摸事件监听
        progressLand.setOnTouchListener(this);
    }

    /**
     * 标题退出监听
     */
    private class backClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (mActivity != null && mActivity.get() != null) {
                if (isIfCurrentIsFullscreen()) {
                    if (isOnlyLand) {
                        mActivity.get().onBackPressed();
                        return;
                    }
                    exitFull();
                } else {
                    mActivity.get().onBackPressed();
                }
            }
        }
    }

    /**
     * 初始化调用
     *
     * @param activity       当前创建Activity
     * @param lifecycleOwner 事件路由
     * @param callBack       接口回调监听
     */
    public void init(FragmentActivity activity, LifecycleOwner lifecycleOwner, CallBack callBack) {
        //设置播放比例
        GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_16_9);
        mActivity = new WeakReference<>(activity);
        orientationUtils = new OrientationUtils(activity, this);
        orientationUtils.setEnable(false);
        //否更新系统旋转，false的话，系统禁止旋转也会跟着旋转
        setRotateWithSystem(false);
        //全屏动画
        setShowFullAnimation(true);
        //设置触摸显示控制ui的消失时间
        setDismissControlTime(5000);
        //设置状态变化监听
        setGSYStateUiListener(mGSYStateUiListener);
        //事件刷新
        mLifecycleOwner = lifecycleOwner;
        mCallBack = callBack;
        //绑定生命周期
        mLifecycleOwner.getLifecycle().addObserver(this);
        //设置播放过程中的回调
        setVideoAllCallBack(sampleCallBack);
        //进度回调
        setGSYVideoProgressListener(videoProgressListener);
        //是否可以滑动界面改变进度，声音等 默认true
//        setIsTouchWiget(NetworkUtil.checkConnection(activity));
        ///不需要屏幕旋转
        setNeedOrientationUtils(true);
        //是否需要全屏锁定
        setNeedLockFull(true);
        //注册广播
        registReceiver();
        //设置屏幕显示方式
        forceLandScreen();
    }


    /**
     * 开始播放
     */
    public void playVideo() {
        //启动-取消控件视图计时器
        startDismissControlViewTimer();
        //播放按键点击
        clickStartIcon();

    }

    /**
     * 播放器SeekBar进度监听
     */
    private final GSYVideoProgressListener videoProgressListener = new GSYVideoProgressListener() {
        @Override
        public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
            // Log.d(TAG, "onProgress: progress=" + progress + " secProgress=" + secProgress + " currentPosition=" + currentPosition + " duration=" + duration);
            if (mCallBack != null) {
                mCallBack.progress(currentPosition, duration);
            }
        }
    };

    private final GSYSampleCallBack sampleCallBack = new GSYSampleCallBack() {

        @Override
        public void onPlayError(String url, Object... objects) {
            // Log.i(TAG, "onPlayError: ");
        }

        @Override
        public void onClickStartIcon(String url, Object... objects) {
            super.onClickStartIcon(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClickResume(String url, Object... objects) {
            super.onClickResume(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//            Logger.getLogger().e("psq --- 点击了暂停状态下的开始按键--->播放");
        }

        @Override
        public void onClickResumeFullscreen(String url, Object... objects) {
            super.onClickResume(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClickStop(String url, Object... objects) {
            super.onClickStop(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClickStopFullscreen(String url, Object... objects) {
            super.onClickStopFullscreen(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onAutoComplete(String url, Object... objects) {
            super.onAutoComplete(url, objects);
            try {
                if (mActivity != null && mActivity.get() != null) {
                    mActivity.get().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (mCallBack != null) {
                mCallBack.complete();
            }
        }

        @Override
        public void onComplete(String url, Object... objects) {
            super.onComplete(url, objects);
        }
    };


    public void updateCtlStyle() {
        llTitleBarLand.setVisibility(isOnlyLand ? VISIBLE : GONE);
        progressLand.setProgress(mProgressBar.getProgress());
        progressLand.setSecondaryProgress(mProgressBar.getSecondaryProgress());
        mProgressBar = progressLand;

        //当前播放进度时长
        String txt = mCurrentTimeTextView.getText() + "";
        mCurrentTimeTextView = currentLand;
        mCurrentTimeTextView.setText(txt);

        //播放播放总时间
        txt = mTotalTimeTextView.getText() + "";
        mTotalTimeTextView = totalLand;
        mTotalTimeTextView.setText(txt);

        //判断当前网络连接状态,播放器是否准备好
        if (NetworkUtil.checkConnection(CarGuo.getInstance().getApplicationContext())) {
            ctlContainerLand.setVisibility(VISIBLE);
        } else {
            ctlContainerLand.setVisibility(GONE);
        }

    }

    /**
     * 状态变化监听
     */
    private final GSYStateUiListener mGSYStateUiListener = new GSYStateUiListener() {
        @Override
        public void onStateChanged(int state) {
            if (mPlayStateListener != null) {
                mPlayStateListener.onStateChanged(state);
            }
            switch (state) {
                //正常
                case CURRENT_STATE_NORMAL:
                    // Log.i(TAG, "play state CURRENT_STATE_NORMAL");
                    break;
                //准备中
                case CURRENT_STATE_PREPAREING:
                    // Log.i(TAG, "play state CURRENT_STATE_PREPAREING");
                    break;
                //开始缓冲
                case CURRENT_STATE_PLAYING_BUFFERING_START:
                    // Log.i(TAG, "play state CURRENT_STATE_PLAYING_BUFFERING_START");
                    break;
                //暂停
                case CURRENT_STATE_PAUSE:
                    // Log.i(TAG, "play state CURRENT_STATE_PAUSE");
                    break;
                //自动播放结束
                case CURRENT_STATE_AUTO_COMPLETE:
                    // Log.i(TAG, "play state CURRENT_STATE_AUTO_COMPLETE");
                    break;
                //错误状态
                case CURRENT_STATE_ERROR:
                    //  Log.d(TAG, "onStateChanged:--------- ");
                    updateLayout();
                    break;

            }
        }
    };

    /**
     * 注册网络监听
     */
    public void registReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        if (mActivity != null && mActivity.get() != null) {
            mActivity.get().registerReceiver(mReceiver, filter);
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                if (NetworkUtil.checkConnection(context)) {
                    updateLayout();
                    switch (mCurrentState) {
                        //正常
                        case CURRENT_STATE_NORMAL:
                            break;
                        //准备中
                        case CURRENT_STATE_PREPAREING:
                            break;
                        //播放中
                        case CURRENT_STATE_PLAYING:
                            break;
                        //开始缓冲
                        case CURRENT_STATE_PLAYING_BUFFERING_START:
                            break;
                        //暂停
                        case CURRENT_STATE_PAUSE:
                            break;
                        //自动播放结束
                        case CURRENT_STATE_AUTO_COMPLETE:
                            break;
                        //错误状态
                        case CURRENT_STATE_ERROR:
                            break;
                    }
                    dismissDialog();
                } else {
//                        flProjection.setVisibility(View.GONE);
                    onVideoPause();
                    updateLayout();
                }
            }
        }
    };

    public void updateLayout() {
        boolean hasNet = NetworkUtil.checkConnection(CarGuo.getInstance().getApplicationContext());
        boolean isPlaying = mCurrentState == CURRENT_STATE_PLAYING;

        if (hasNet || isPlaying) {
            //点击播放按钮播放VISIBLE
            if (isIfCurrentIsFullscreen()) {
                flCenterPlay.setVisibility(VISIBLE);
            } else {
                flCenterPlay.setVisibility(GONE);
            }
        } else {
            if (isIfCurrentIsFullscreen()) {
                flCenterPlay.setVisibility(GONE);
            }
        }

        if (hasNet && mCurrentState == CURRENT_STATE_PAUSE) {
            setViewShowState(mStartButton, VISIBLE);
        }
        if (hasNet || isPlaying) {
            ctlContainerLand.setVisibility(VISIBLE);
        } else if (mCurrentState != CURRENT_STATE_PLAYING) {
            if (isIfCurrentIsFullscreen()) {
                //显示无网络布局
                showNetDialog();
            } else {
                dismissDialog();
            }
        }


    }

    /**
     * 设置数据并准备播放
     */
    @SuppressLint("StaticFieldLeak")
//    public void setDataAndPlay(MediaDto dto) {
//
//        if (mPlayTask != null && !mPlayTask.isCancelled()) {
//            try {
//                mPlayTask.cancel(true);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        mPlayTask = new AsyncTask<Void, Void, Void>() {
//            @Override
//            protected Void doInBackground(Void... voids) {
//                try {
//                    mCurPlayMediaDto = dto;
//                    id = dto.getId();
//                    //名称过滤.MSKT后缀
//                    if (mCurPlayMediaDto.getName() != null && mCurPlayMediaDto.getName().contains(".MSKT")) {
//                        mCurPlayMediaDto.setName(mCurPlayMediaDto.getName().substring(0, mCurPlayMediaDto.getName().lastIndexOf(".")));
//                    }
//
//                    if (!TextUtils.isEmpty(dto.getFilePath()) && new File(dto.getFilePath()).exists()) {
//                        url = dto.getFilePath();
//                    } else {
//                        url = getDefaultUrl();
//                    }
//
//                    if (EncodeUtil.isEncryptedFile(url) || EncodeUtil.isEncryptedUrl(url)) {
//                        url = EncodeUtil.getEncodeUrl(url);
//                    }
//                    return null;
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            }
//
//            @Override
//            protected void onPostExecute(Void unused) {
//                try {
//                    mTextureViewContainer.removeAllViews();
//                    //暂时VISIBLE
//                    if (isIfCurrentIsFullscreen()) {
//                        flCenterPlay.setVisibility(VISIBLE);
//                    } else {
//                        flCenterPlay.setVisibility(GONE);
//                    }
//                    onVideoReset();
//                    canStatistics = true;
//                    play();
//                    // flNotNetLand.setVisibility(GONE);//隐藏横屏无网络布局
//                    dismissDialog();
//                    ctlContainerLand.setVisibility(VISIBLE);//显示横屏底部控制条
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        };
//        mPlayTask.execute();
//
//
//    }

    /**
     * 开始播放
     */
    private void play() {
        //设置url
        setUp(url, true, "标题");
//        titleLand.setText(mCurPlayMediaDto.getName());
//        GlideUtils.loadVideoCover(ivVideoCover, mCurPlayMediaDto.getCoverUrl());
    }

    /**
     * 默认小屏还是全屏
     */
    public void forceLandScreen() {
        if (orientationUtils != null) {
            setIfCurrentIsFullscreen(isOnlyLand);
            updateCtlStyle();
            mCallBack.onFull(orientationUtils, isOnlyLand);
            updateLayout();
        }
    }

    /**
     * @return 获取路径
     */
    private String getDefaultUrl() {
//        String url = "";
//        List<VideoDto> list = mCurPlayMediaDto.getList();
//        for (VideoDto videoDto : list) {
//            if (videoDto.isDefault()) {
//                url = videoDto.getVideoUrl();
//                break;
//            }
//        }
//        if (TextUtils.isEmpty(url)) {
//            url = list.get(0).getVideoUrl();
//        }
        //Log.e(TAG, "url=" + url);
        return url;
    }


    /**
     * 设置全屏
     */
    public void setFull() {
        if (orientationUtils != null && !isIfCurrentIsFullscreen() && (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE || mCurrentState == CURRENT_STATE_NORMAL)) {
            //是否全屏
            setIfCurrentIsFullscreen(true);
            updateCtlStyle();
            //全屏按钮
            setViewShowState(flFull, GONE);
            setViewShowState(llTitleBarLand, VISIBLE);
            mCallBack.onFull(orientationUtils, true);
            updateLayout();
            surfaceContainer.setBackgroundColor(0xff000000);
        }
    }

    /**
     * 退出全屏
     */
    public void exitFull(){
        setIfCurrentIsFullscreen(false);
        setViewShowState(llTitleBarLand, VISIBLE);
        updateCtlStyle();
        mCallBack.onFull(orientationUtils, false);
        updateLayout();
    }

    /**
     * 更新播放状态
     */
    @Override
    protected void updateStartImage() {
        ImageView imageView = (ImageView) mStartButton;
        if (mCurrentState == CURRENT_STATE_PLAYING) {
            imageView.setVisibility(GONE);
            ivPlay.setImageResource(R.mipmap.icon_zt);
        } else {
            imageView.setImageResource(R.mipmap.icon_bf);
            ivPlay.setImageResource(R.mipmap.icon_bf);
        }
    }


    @Override
    protected void changeUiToClear() {
        super.changeUiToClear();
    }

    /**
     * 播放完成且标题栏显示
     */
    @Override
    protected void changeUiToCompleteClear() {
        // Log.i(TAG, "changeUiToCompleteClear");
        setViewShowState(mTopContainer, isIfCurrentIsFullscreen() ? View.VISIBLE : View.INVISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, VISIBLE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        updateStartImage();
    }

    /**
     * 播放完成且标题栏未显示
     */
    @Override
    protected void changeUiToCompleteShow() {
        // Log.i(TAG, "changeUiToCompleteShow");
        setViewShowState(mTopContainer, isIfCurrentIsFullscreen() ? View.VISIBLE : View.INVISIBLE);
        setViewShowState(mBottomContainer, VISIBLE);
        setViewShowState(mStartButton, VISIBLE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        updateStartImage();

    }

    /**
     * 重写此方法 处理无网络时，mTopContainer迅速隐藏的问题
     */
    @Override
    protected void changeUiToError() {
        setViewShowState(mBottomContainer, INVISIBLE);
        setViewShowState(mStartButton, VISIBLE);
        setViewShowState(mLoadingProgressBar, INVISIBLE);
        setViewShowState(mThumbImageViewLayout, INVISIBLE);
        setViewShowState(mBottomProgressBar, INVISIBLE);
        updateStartImage();
    }


    @Override
    protected void changeUiToNormal() {
        super.changeUiToNormal();
    }

    @Override
    protected void changeUiToPauseClear() {
        super.changeUiToPauseClear();
    }


    @Override
    protected void changeUiToPauseShow() {
        super.changeUiToPauseShow();
        updateLayout();
    }

    @Override
    protected void changeUiToPlayingBufferingClear() {
        super.changeUiToPlayingBufferingClear();
    }


    @Override
    protected void changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow();
    }

    @Override
    protected void changeUiToPlayingClear() {
        super.changeUiToPlayingClear();
    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
    }

    @Override
    protected void changeUiToPrepareingClear() {
        super.changeUiToPrepareingClear();
    }

    @Override
    protected void changeUiToPreparingShow() {
        super.changeUiToPreparingShow();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        if (canResume) {
            onVideoResume();
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        // Log.i(TAG, "onPause");
        //判断onPause的状态，如果是播放中，则在恢复到onResume时需要恢复播放，否则不恢复播放
        canResume = mCurrentState == CURRENT_STATE_PLAYING;
        onVideoPause();
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        if (mActivity != null && mActivity.get() != null) {
            mActivity.get().unregisterReceiver(mReceiver);
        }
        setVideoAllCallBack(null);
        setGSYVideoProgressListener(null);
        GSYVideoManager.releaseAllVideos();
        mLifecycleOwner.getLifecycle().removeObserver(this);
        mLifecycleOwner = null;
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
        if (mPlayTask != null && !mPlayTask.isCancelled()) {
            mPlayTask.cancel(true);
        }
        release();
    }

    /**
     * 接口回调使用
     */
    public interface CallBack {
        void complete();

        void progress(int currentPosition, int duration);

        void onFull(OrientationUtils orientationUtils, boolean isLand);
    }


    public interface SeekOnStartCallBack {
        void onSeekOnStartProgress();  //播放进度
    }

    /**
     * 无网络
     */
    public void showNetDialog() {
//        CheckNetWorkPopup popup = new CheckNetWorkPopup(getContext());
//        popup.setOnConfirmListener(isConfirm -> {
//            if (isConfirm) {
//                // 重新加载
//                AppInterfaceUtils.toWlanPage(getContext());
//                dismissDialog();
//            }
//        });
//        xPopup = new XPopup.Builder(getContext())
//                .hasNavigationBar(false).isDestroyOnDismiss(true).isRequestFocus(false).asCustom(popup).show();
    }

    private void dismissDialog() {
//        if (xPopup != null) {
//            xPopup.dismiss();
//            xPopup = null;
//        }

    }

    /**
     * 滑动触摸事件
     * 增加SeekBar灵敏度
     */
    private final View.OnTouchListener mSeekBarParentTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (mProgressBar == null || mProgressBar.getProgress() == 0) {
                return false;
            }
            Rect seekRect = new Rect();
            mProgressBar.getHitRect(seekRect);

            if ((event.getY() >= (seekRect.top - 100)) && (event.getY() <= (seekRect.bottom + 100))
                    && event.getX() >= seekRect.left /*&& event.getX() <= seekRect.right*/) {
                float y = seekRect.top + seekRect.height() / 2;
                float x = event.getX() - seekRect.left;//seekBar只接受相对x位置
                if (x < 0) {
                    x = 0;
                } else if (x > seekRect.width()) {
                    x = seekRect.width();
                }
                MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(),
                        event.getAction(), x, y, event.getMetaState());
                return mProgressBar.onTouchEvent(me);

            }
            return false;
        }
    };
}
